package sc.love.boot.kafka;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;


@Component
public class KafkaProducer {

    @Autowired
    private KafkaTemplate kafkaTemplate;

    private Gson gson = new GsonBuilder().create();

    //发送消息方法
    public void send(String name,String topic) {
        try {
            Message message = new Message();
            message.setId(System.currentTimeMillis());
            message.setMsg(name);
            message.setSendTime(new Date().toString());
            System.out.println("kafka start producer");
            kafkaTemplate.send(topic, gson.toJson(message));
            System.out.println("kafka end producer");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
